package com.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Category;
import com.sky.entity.Employee;
import com.sky.exception.AccountNotFoundException;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Info;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("员工登录")
    public Result<EmployeeLoginVO> empLogin(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录...");

        Employee employee = employeeService.login(employeeLoginDTO);

        //System.out.println("666"+BaseContext.getCurrentId());
        String adminSecretKey = jwtProperties.getAdminSecretKey();
        String adminTokenName = jwtProperties.getAdminTokenName();
        long adminTtl = jwtProperties.getAdminTtl();
        Map<String, Object> claims = new HashMap<>();

        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String jwt = JwtUtil.createJWT(adminSecretKey, adminTtl, claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(jwt)
                .build();

        return Result.success(employeeLoginVO);

    }

    @PostMapping("/logout")
    @ApiOperation("员工退出")
    public Result<String> logout() {
        log.info("员工退出...");
        return Result.success();
    }

    @ApiOperation("新增员工")
    @PostMapping
    public Result save(@RequestBody EmployeeDTO employeeDTO) {
        log.info("新增员工...");
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);
        employeeService.save(employee);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("员工分页查询")
    public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO) {
        log.info("员工分页查询...");
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page1 = new Page(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(employeePageQueryDTO.getName() != null, Employee::getName, employeePageQueryDTO.getName())
                .orderByDesc(Employee::getCreateTime);;
        page1 = employeeService.page(page1, queryWrapper);
        long count = employeeService.count();
        PageResult pageResult = new PageResult();
        pageResult.setTotal(count);
        pageResult.setRecords(page1.getRecords());
        return Result.success(pageResult);
    }

    @ApiOperation("启用、禁用员工")
    @PostMapping("/status/{status}")
    public Result stop(@PathVariable int status,Long id) {
        log.info("启用、禁用员工...");
        Employee employee = employeeService.getById(id);
        employee.setStatus(status);
        LambdaUpdateWrapper<Employee> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Employee::getId,id).set(Employee::getStatus,status);
        employeeService.update(employee,lambdaUpdateWrapper);
        return Result.success();
    }

    @ApiOperation("编辑员工信息")
    @PutMapping
    public Result updateEmp(@RequestBody EmployeeDTO employeeDTO){
        log.info("编辑员工信息...");
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        LambdaUpdateWrapper<Employee> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(employee.getStatus()!= StatusConstant.DISABLE,Employee::getId,employee.getId());
        employeeService.update(employee,lambdaUpdateWrapper);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询员工")
    public Result<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工...");
        Employee employee = employeeService.getById(id);
        return Result.success(employee);
    }

    @PutMapping("/editPassword")
    @ApiOperation("修改密码")
    public Result editPassword(@RequestBody PasswordEditDTO passwordEditDTO){
        log.info("修改密码...");
        Employee employee = new Employee();
        employee.setId(BaseContext.getCurrentId());
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        employee.setPassword(newPassword);

        String oldPassword = passwordEditDTO.getOldPassword();
        oldPassword= DigestUtils.md5DigestAsHex(oldPassword.getBytes());

        LambdaUpdateWrapper<Employee> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Employee::getId,BaseContext.getCurrentId())
                .eq(passwordEditDTO.getOldPassword()!=null,Employee::getPassword,oldPassword);
        boolean flat = employeeService.update(employee, lambdaUpdateWrapper);
        if(flat){
            return Result.success();
        }
        else return Result.error("原始密码错误...");
    }

}
